from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseRedirect
from .models import Question, Choice
from django.template import loader
from django.urls import reverse # 类似前端模板语言url函数
from django.views import generic



# def index(request):
#     return HttpResponse("""
#     <!DOCTYPE html>
#         <html lang="en">
#             <head>
#             <meta charset="UTF-8">
#             <title>Title</title>
#             </head>
# <body>
# <h1>hello world</h1>
# </body>
# </html>""")
# def index(request):
#     """
#     展示问题列表
#     """
#     question_list = Question.objects.all().order_by('-pub_date')[0:2]
#     # print(question_list)
#     # output = ''
#     # for i in question_list:
#     #     print(i.id, i.question_text, i.pub_date)
#     #     output = output + i.question_text + ','
#     # print(output)
#     # output = ','.join([i.question_text for i in question_list])
#     template = loader.get_template('polls/index.html')
#     context = {'question_list': question_list}
#     return HttpResponse(template.render(context, request))o
def index(request):
    question_list = Question.objects.order_by('-pub_date')[:2]
    context = {'question_list': question_list}
    return render(request, 'polls/index.html', context=context)

def detail(request, question_id):
    """
    显示一个问题的详细信息，问题内容， 问题发布时间、选项内容， 每个选项的投票数
    """
    try:
        question = Question.objects.get(id=question_id)
        print(question)

        # choices = Choice.objects.filter(question=question.id)
        # 由于orm 代劳， question 直接带出对应的choices
        # choices = question.choice_set.all()
        # 由于前端模板语言本质是后端代码，可以把上句话放在HTML页面中写，有助于降低后端复杂度
    except Question.DoesNotExist:
        raise Http404("404，此ID的问题不存在")
    print(question)
    context = {
        'question': question,
    }
    return render(request, 'polls/detail.html', context)

    # 写法3：
    # question = get_object_or_404(Question, id=question_id)
    # print(question)
    # return render(request, 'polls/detail.html', {'question': question})


def results(request, question_id):
    """
    投票结果
    """
    question = Question.objects.get(id=question_id)
    return render(request, 'polls/results.html', {'question': question})


def vote(request, question_id):
    """
    投票
    """
    try:
        question = Question.objects.get(id=question_id)
        choices = question.choice_set.all()
        choices_id = request.POST['choice']
        selected_choice = question.choice_set.get(id=choices_id)
    except Question.DoesNotExist as e:
        error_message = '问题内容不存在，检查问题id'
    except Choice.DoesNotExist as e:
        error_message = '问题的选项不存在'
        return render(request, 'polls/detail.html',context={
            'question': question,
            'error_message': error_message
        })
    else:
        # sql update choice set votes=votes+1 where id=2
        selected_choice.votes += 1
        # commit;
        selected_choice.save()
        # 投完票重定向到views.results(qid)
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
    print('同九年，汝何秀')


# 通用模板示例，跟def index类比着看
class SimpleView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'question_list'

    def get_queryset(self):
        return Question.objects.all()
